<template>
    <el-dialog class="ui-goods-category-dialog" v-model="dialogVisible" title="更多设置" ref="dialog"  @opened="init" :beforeClose="beforeClose" @closed="finalThings">
        <el-tabs v-model="activeName">
            <el-tab-pane label="分类" name="category">
                <el-table :data="data" ref="dragabletable" class="move-table" row-key="id">
                    <el-table-column prop="name" label="分类名称">
                        <template #default="scope">
                            <div style="display: flex;">
                                <el-icon 
                                    :size="18"
                                    v-if="!scope.row.def"
                                    :class="[scope.row.def ? 'forbid' : 'goods_move_class']"
                                    style="cursor: pointer;margin-right: 5px;margin-top: 2px;"
                                >
                                    <DCaret />
                                </el-icon>
                                <div>{{ scope.row.name }}</div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" fixed="right" width="120">
                        <template #header>
                            <div style="text-align:center"><el-button link size="small" type="primary" @click="onAddCategory()">添加</el-button></div>
                        </template>
                        <template #default="scope">
                            <el-button-group size="small">
                                <el-button type="primary" :disabled="scope.row.def" @click="onUpdateCategory(scope.row,scope.$index)">修改</el-button>
                                <el-button type="danger" :disabled="scope.row.def" @click="onDestroyCategory(scope.row,scope.$index)">删除</el-button>
                            </el-button-group>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
            <el-tab-pane label="其他" name="other">
                
            </el-tab-pane>
        </el-tabs>
    </el-dialog>
</template>
<script>
import { reactive, toRefs,onMounted } from 'vue'
import { useSocket } from '../../uiframe/services/socket';
import Sortable from "sortablejs"
import { DCaret } from '@element-plus/icons-vue';
import { UiShowDialog } from '../../uiframe/layout/components/CompFactory.vue';
import CreateGoodCategoryDialog from './CreateGoodCategoryDialog.vue';
import { ElMessageBox } from 'element-plus';

export default {
    components:{
        DCaret
    },
    props:{
        q:Object,
        _compId:Number,
        done: Function
    },
    setup(props)
    {
        let changed = false,data = reactive({
            data:[],
            dialogVisible: true,
            activeName:'category',
            dragabletable:null,
            category:''
        });

        const load = () => {
            useSocket().then(socket=>{
                socket.rpc('category', {}).then(({success,data:result})=>{
                    data.data = result;
                })
            })
        },
        onfailure = (msg) => { ElMessage({ type: 'error', message: msg.message }) },
        onsuccess = (msg) => { ElMessage({ type: 'success', message: msg.message }) },
        events = {
            onCancel : ()=>data.dialogVisible = false,
            finalThings: () =>{
                if(changed) props.q.resolve({success:true,message:'', data:[]});
                props.done()
            }
        },
        methods = {
            init:()=>{
                const tbody = data.dragabletable.$el.querySelector(`tbody`);
                Sortable.create(tbody, {
                    group: {
                        name: "name",
                        pull: true,
                        put: true,
                    },
                    handle: ".goods_move_class",
                    filter:".forbid",
                    easing: 'cubic-bezier(1, 0, 0, 1)',
                    onMove(e){
                        let i = e.related.querySelector(`.el-icon`);
                        return i ? true : false;
                    },
                    onEnd({oldIndex,newIndex}) {
                        let payload = [data.data[oldIndex].id, data.data[newIndex].id];
                        if (oldIndex !== newIndex) {
                            useSocket().then(socket=>socket.rpc('move_category', payload).then(res=>{
                                res.success ? onsuccess(res) : onfailure(res)
                                if(res.success) changed = true;
                            }).catch(res=>{
                                onfailure(res)
                            }))
                            const currRow = data.data.splice(oldIndex, 1)[0];
                            data.data.splice(newIndex, 0, currRow);
                        }
                    }
                });
            },
            beforeClose:(next)=>{
                next();
            },
            onUpdateCategory:(row,index)=>{
                UiShowDialog(CreateGoodCategoryDialog,{payload:row}).then(res=>{
                    data.data[index] = res.data;
                    changed = true;
                }).catch(res=>{})
            },
            onDestroyCategory:(row,index)=>{
                ElMessageBox.confirm(`您确定要删除名字为"${row.name}"的分类么?`).then(()=>{
                    useSocket().then(socket=>socket.rpc('remove_category', {id:row.id}).then(res=>{
                        res.success ? onsuccess(res) : onfailure(res)
                        if(res.success){
                            changed = true;
                            data.data.splice(index,1);
                        }
                    }).catch(res=>{
                        onfailure(res)
                    }))
                }).catch(()=>{})
            },
            onAddCategory:()=>{
                UiShowDialog(CreateGoodCategoryDialog,{payload:{name:''}}).then(res=>{
                    data.data.push(res.data);
                    changed = true;
                }).catch(res=>{})
            }
        }
        
        load();
        return {
            ...toRefs(data),
            ...methods,
            ...events
        }
    }
}
</script>

<style lang="scss">
.ui-goods-category-dialog{
    width: 36rem;
    max-width: 36rem;
    min-width: 36rem;
    .el-dialog__body{
        padding-top:.5rem;
        padding-left:.5rem;
        padding-right:.5rem;
    }
    .el-dialog__footer{
        border-top: 1px solid #e4e7ed;
    }
    .move-table{
        user-select: none;
    }
}
</style>